import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ApiDetailResponse } from '@/types'

interface DialogState {
  visible: boolean
  loading: boolean
  title: string
}

/**
 * 通用对话框管理组合式函数
 * @param defaultTitle 默认标题
 * @returns 对话框状态和操作方法
 */
export function useDialog(defaultTitle: string = '') {
  const state = reactive<DialogState>({
    visible: false,
    loading: false,
    title: defaultTitle,
  })

  /**
   * 打开对话框
   */
  const openDialog = (title?: string) => {
    state.visible = true
    state.title = title || defaultTitle
  }

  /**
   * 关闭对话框
   */
  const closeDialog = () => {
    state.visible = false
    state.loading = false
  }

  /**
   * 设置加载状态
   */
  const setLoading = (loading: boolean) => {
    state.loading = loading
  }

  /**
   * 设置标题
   */
  const setTitle = (title: string) => {
    state.title = title
  }

  return {
    // 状态
    visible: state.visible,
    loading: state.loading,
    title: state.title,

    // 方法
    openDialog,
    closeDialog,
    setLoading,
    setTitle,
  }
}

/**
 * 删除确认组合式函数
 * @param deleteApi 删除API函数
 * @param onSuccess 删除成功回调
 * @returns 删除方法
 */
export function useDelete<T = any>(
  deleteApi: (id: number | string) => Promise<ApiDetailResponse<T>>,
  onSuccess?: () => void
) {
  /**
   * 确认删除
   */
  const confirmDelete = async (
    id: number | string,
    message: string = '确定要删除此项吗？删除后无法恢复！'
  ) => {
    try {
      await ElMessageBox.confirm(message, '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false,
      })

      const response = await deleteApi(id)

      if (response.code === 0) {
        ElMessage.success('删除成功')
        onSuccess?.()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  }

  /**
   * 批量删除确认
   */
  const confirmBatchDelete = async (
    ids: (number | string)[],
    batchDeleteApi: (ids: (number | string)[]) => Promise<ApiDetailResponse<any>>,
    message: string = `确定要删除选中的 ${ids.length} 项吗？删除后无法恢复！`
  ) => {
    if (ids.length === 0) {
      ElMessage.warning('请选择要删除的数据')
      return
    }

    try {
      await ElMessageBox.confirm(message, '批量删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })

      const response = await batchDeleteApi(ids)

      if (response.code === 0) {
        ElMessage.success(`成功删除 ${ids.length} 项数据`)
        onSuccess?.()
      } else {
        ElMessage.error(response.msg || '批量删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败，请稍后重试')
      }
    }
  }

  return {
    confirmDelete,
    confirmBatchDelete,
  }
}
